package com.videogo;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.csun.nusing.App;
import com.csun.nusing.bean.UrlBean;
import com.csun.nusing.bean.jsonbean.StringDataBean;
import com.csun.nusing.util.SPUtils;
import com.google.gson.Gson;
import com.home.administrator.okhttplibrary.IOkTaskCallback;
import com.home.administrator.okhttplibrary.OkHttpTask;
import com.videogo.constant.IntentConsts;
import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.BaseException;
import com.videogo.exception.ErrorCode;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.scan.main.CaptureActivity;
import com.videogo.util.ConnectionDetector;
import com.videogo.util.DateTimeUtil;
import com.videogo.util.EZUtils;
import com.videogo.util.LogUtil;
import com.videogo.util.RemoteListContant;
import com.videogo.util.SelectCameraDialog;
import com.videogo.util.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.csun.nusing.R;


public class VideoListActivity extends Activity {

    protected static final String TAG = "VideoList";
    private int mErrorCode;// 错误码
    private EZCameraListAdapter mAdapter = null;
    private ListView mListView = null;
    private ImageView mAddBtn;
    private TextView mMyDevice;
    public final static int REQUEST_CODE = 100;
    public final static int RESULT_CODE = 101;
    private String authorization;
    private VideoListBean bean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_list);
        initSDK();
        initView();
    }

    private void initSDK() {
        //getToken
        authorization = (String) SPUtils.get(this, "authorization", "");
        Map<String, String> param = new HashMap<String, String>();
        OkHttpTask.newInstance(this).post(param, OkHttpTask.OkHttpTaskBuidler.OkType.form)
                .addHeader("authorization", authorization)
                .enqueue(new IOkTaskCallback() {
                    @Override
                    public void onSuccess(String result) {
                        Log.e("-----", "----" + result);
                        Gson gson = new Gson();
                        if (result != null) {
                            StringDataBean bean = gson.fromJson(result, StringDataBean.class);
                            if (bean != null) {
                                App.getOpenSDK()
                                        .setAccessToken(bean.getData());
                            } else {
                                App.getOpenSDK()
                                        .setAccessToken(
                                                "at.37x0vs1w8y9f2ps82vzyzz9n4cwbqrr8-6beflmcohu-027x88d-g0ossi2ch");
                            }
                        }
                    }
                }).start(UrlBean.GetVideoTokenURL);
        OkHttpTask.newInstance(this).post(param, OkHttpTask.OkHttpTaskBuidler.OkType.form)
                .addHeader("authorization", authorization)
                .enqueue(new IOkTaskCallback() {
                    @Override
                    public void onSuccess(String result) {
                        Log.e("-----", "----" + result);
                        Gson gson = new Gson();
                        if (result != null) {
                             bean = gson.fromJson(result, VideoListBean.class);
                            if (bean!=null&&bean.isStatus()){
                                getData();
                            }
                        }
                    }
                }).start(UrlBean.VideoListURL);
    }

    private void initView() {
        mAdapter = new EZCameraListAdapter(this);
        mListView = (ListView) findViewById(R.id.camera_listview);
        mListView.setAdapter(mAdapter);
        findViewById(R.id.videolist_back_iv).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mAddBtn = (ImageView) findViewById(R.id.btn_add);
        mAddBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                add();
            }
        });
        mAdapter.setOnClickListener(new EZCameraListAdapter.OnClickListener() {
            @Override
            public void onPlayClick(BaseAdapter adapter, View view, int position) {
                final EZDeviceInfo deviceInfo = mAdapter.getItem(position);
                if (deviceInfo.getCameraNum() <= 0 || deviceInfo.getCameraInfoList() == null || deviceInfo.getCameraInfoList().size() <= 0) {
                    LogUtil.d(TAG, "cameralist is null or cameralist size is 0");
                    return;
                }
                if (deviceInfo.getCameraNum() == 1 && deviceInfo.getCameraInfoList() != null && deviceInfo.getCameraInfoList().size() == 1) {
                    LogUtil.d(TAG, "cameralist have one camera");
                    final EZCameraInfo cameraInfo = EZUtils.getCameraInfoFromDevice(deviceInfo, 0);
                    if (cameraInfo == null) {
                        return;
                    }

                    Intent intent = new Intent(VideoListActivity.this, VideoPlayerActivity.class);
                    intent.putExtra(IntentConsts.EXTRA_CAMERA_INFO, cameraInfo);
                    intent.putExtra(IntentConsts.EXTRA_DEVICE_INFO, deviceInfo);
                    startActivityForResult(intent, REQUEST_CODE);
                    return;
                }
                SelectCameraDialog selectCameraDialog = new SelectCameraDialog();
                selectCameraDialog.setEZDeviceInfo(deviceInfo);
                selectCameraDialog.setCameraItemClick(new cameraitemclick());
                selectCameraDialog.show(getFragmentManager(), "onPlayClick");
            }

            @Override
            public void onRemotePlayBackClick(BaseAdapter adapter, View view, int position) {
                EZDeviceInfo deviceInfo = mAdapter.getItem(position);
                if (deviceInfo.getCameraNum() <= 0 || deviceInfo.getCameraInfoList() == null || deviceInfo.getCameraInfoList().size() <= 0) {
                    LogUtil.d(TAG, "cameralist is null or cameralist size is 0");
                    return;
                }
                if (deviceInfo.getCameraNum() == 1 && deviceInfo.getCameraInfoList() != null && deviceInfo.getCameraInfoList().size() == 1) {
                    LogUtil.d(TAG, "cameralist have one camera");
                    EZCameraInfo cameraInfo = EZUtils.getCameraInfoFromDevice(deviceInfo, 0);
                    if (cameraInfo == null) {
                        return;
                    }
                    Intent intent = new Intent(VideoListActivity.this, VideoPlaybackActivity.class);
                    intent.putExtra(RemoteListContant.QUERY_DATE_INTENT_KEY, DateTimeUtil.getNow());
                    intent.putExtra(IntentConsts.EXTRA_CAMERA_INFO, cameraInfo);
                    startActivity(intent);
                    return;
                }
                SelectCameraDialog selectCameraDialog = new SelectCameraDialog();
                selectCameraDialog.setEZDeviceInfo(deviceInfo);
                selectCameraDialog.setCameraItemClick(new cameraitemclick());
                selectCameraDialog.show(getFragmentManager(), "RemotePlayBackClick");
            }

            @Override
            public void onSetDeviceClick(BaseAdapter adapter, View view, int position) {
                EZDeviceInfo deviceInfo = mAdapter.getItem(position);
                Intent intent = new Intent(VideoListActivity.this, VideoSettingActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelable(IntentConsts.EXTRA_DEVICE_INFO, deviceInfo);
                intent.putExtra("Bundle", bundle);
                startActivityForResult(intent, 0x11);
            }

            @Override
            public void onDeleteClick(BaseAdapter adapter, View view, int position) {
            }

            @Override
            public void onAlarmListClick(BaseAdapter adapter, View view, int position) {
                final EZDeviceInfo deviceInfo = mAdapter.getItem(position);
                Intent intent = new Intent(VideoListActivity.this, VideoMessageActivity.class);
                intent.putExtra(IntentConsts.EXTRA_DEVICE_ID, deviceInfo.getDeviceSerial());
                startActivity(intent);
            }

            @Override
            public void onDevicePictureClick(BaseAdapter adapter, View view, int position) {
            }

            @Override
            public void onDeviceVideoClick(BaseAdapter adapter, View view, int position) {
            }

            @Override
            public void onDeviceDefenceClick(BaseAdapter adapter, View view,
                                             int position) {
            }

        });
    }

    // addDevice
    protected void add() {
        //跳转CaptureActivity
        Intent intent = new Intent(this, CaptureActivity.class);
        startActivityForResult(intent, 0x11);
    }

    // 获取设备列表
    private void getData() {
        if (!ConnectionDetector.isNetworkAvailable(this)) {
            mErrorCode = ErrorCode.ERROR_WEB_NET_EXCEPTION;
            return;
        }
        new GetCamersInfoListTask(bean.getData()).execute();
    }

    private class cameraitemclick implements SelectCameraDialog.CameraItemClick {

        @Override
        public void onCameraItemClick(EZDeviceInfo deviceInfo, int camera_index) {

        }
    }

    private class GetCamersInfoListTask extends
            AsyncTask<Void, Void, List<EZDeviceInfo>> {

        private int mErrorCode = 0;
        private List<VideoListBean.VideoListDataBean> data;
        public GetCamersInfoListTask(List<VideoListBean.VideoListDataBean> data) {
            this.data = data;
        }

        @Override
        protected List<EZDeviceInfo> doInBackground(Void... params) {
            if (isFinishing()) {
                return null;
            }
            if (!ConnectionDetector.isNetworkAvailable(VideoListActivity.this)) {
                mErrorCode = ErrorCode.ERROR_WEB_NET_EXCEPTION;
                return null;
            }
            try {
                List<EZDeviceInfo> result = null;
                List<EZDeviceInfo> result2 = new ArrayList<>();
                result = App.getOpenSDK().getDeviceList(0, 100);
                result.addAll(App.getOpenSDK().getSharedDeviceList(0, 100));
                for (int i=0;i<result.size();i++){
                    for (int j=0;j<data.size();j++){
                        if (data.get(j).getDeviceserial().equals(result.get(i).getDeviceSerial())){
                            result2.add(result.get(i));
//性能优化
//                            SPUtils.put(VideoListActivity.this,data.get(j).getDeviceserial(),data.get(j).getVerification());
                            continue;
                        }
                    }
                }
                return result2;
            } catch (BaseException e) {
                ErrorInfo errorInfo = (ErrorInfo) e.getObject();
                mErrorCode = errorInfo.errorCode;
                LogUtil.debugLog("fzq", errorInfo.toString());
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<EZDeviceInfo> result) {
            super.onPostExecute(result);
            if (isFinishing()) {
                return;
            }

            if (result != null) {
                if (mAdapter != null && mAdapter.getCount() == 0) {
                    mAdapter.clearItem();
                }
                addCameraList(result);
                mAdapter.notifyDataSetChanged();
            }

            if (mErrorCode != 0) {
                onError(mErrorCode);
            }
        }

        protected void onError(int errorCode) {
            switch (errorCode) {
                case ErrorCode.ERROR_WEB_SESSION_ERROR:
                case ErrorCode.ERROR_WEB_SESSION_EXPIRE:
                    break;
                default:
                    if (mAdapter.getCount() == 0) {
                        mListView.setVisibility(View.GONE);
                    } else {
                        Utils.showToast(VideoListActivity.this,
                                R.string.get_camera_list_fail, errorCode);
                    }
                    break;
            }
        }
    }

    private void addCameraList(List<EZDeviceInfo> result) {
        int count = result.size();
        EZDeviceInfo item = null;
        for (int i = 0; i < count; i++) {
            item = result.get(i);
            mAdapter.addItem(item);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11 && resultCode == 0x12) {
            getData();
        } else if (requestCode == 0x11 && resultCode == 0x13) {
            for (int i = 0; i < mAdapter.getCount(); i++) {
                mAdapter.removeItem(mAdapter.getItem(i));
            }
            getData();
        }
    }

}
